package services

import (
	"hg/config"
	"hg/enmu"
	"hg/models"
	"hg/pkg/database"
	"hg/pkg/minio/storage"
	"os"
	"path/filepath"
	"time"

	"github.com/sirupsen/logrus"
)

// 插入object到数据库，并上传到云存储，返回完整的object
func InsertObject(filePath string) *models.Object {
	// 读取配置文件
	if filePath == "" {
		logrus.Errorln("FilePath is nil")
		return nil
	}

	conf := config.GetConfig()

	// 打开文件
	file, err := os.Open(filePath)
	if err != nil {
		logrus.Errorln("open file failed")
		return nil
	}
	defer file.Close()

	// 获取文件信息
	fileInfo, err := file.Stat()
	if err != nil {
		logrus.Errorln("failed to get file infomation")
		return nil
	}

	// 将文件内容上传到云存储
	if err = storage.PutObject(conf.BucketName, fileInfo.Name(), fileInfo.Size(), file); err != nil {
		logrus.Errorln("failed to upload file to s3")
		return nil
	}
	objUrl := conf.BucketName + "/" + fileInfo.Name()
	// objUrl := "https://" + conf.BucketName + "." + conf.Endpoint + "/" + fileInfo.Name()
	object := &models.Object{ObjUrl: objUrl}
	ext := filepath.Ext(filePath)
	switch ext {
	case ".mp4", ".avi", ".mkv":
		object.Type = enmu.Video
	case ".jpg", ".png", ".gif":
		object.Type = enmu.Picture
	default:
		object.Type = enmu.ElseType
	}
	object.UploadTime = time.Now()
	object, _ = database.InsertOneObject(object)
	return object
}
